/*
   Author: mahaiyuan
   Date: 2021/7/29 11:00 下午
   Description:
*/
package main

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"time"
)

type Student struct {
	Id         int32     //主键
	StuNo      string    //学号
	Name       string    //姓名
	Gender     int32     //性别
	RegDate    time.Time //入学日期
	CreateTime time.Time //创建时间
}

func main() {
	db, err := sql.Open(
		"mysql",
		"root:root@tcp(127.0.0.1:3306)/gogogo?charset=utf8&parseTime=true&loc=Local",
	)
	defer db.Close()
	if err != nil {
		log.Fatal("connection mysql error.", err)
	}

	student := &Student{
		Id:         0,
		StuNo:      "20210010004",
		Name:       "张三",
		Gender:     1,
		RegDate:    time.Now().Add(time.Hour * -72),
		CreateTime: time.Now(),
	}
	insert(db, student)
}

func insert(db *sql.DB, stu *Student) {
	stmt, err := db.Prepare("INSERT INTO tbl_student (stu_no, name, gender, reg_date, create_time) " +
		"VALUES (?, ?, ?, ?, ?)")
	defer stmt.Close()
	if err != nil {
		log.Fatal("prepare error.", err)
	}
	result, err := stmt.Exec(stu.StuNo, stu.Name, stu.Gender, stu.RegDate, stu.CreateTime)
	if err != nil {
		log.Fatal("exec error.", err)
	}
	rowsAffected, _ := result.RowsAffected() //影响的行数
	lastInsertId, err := result.LastInsertId()	//最后插入的id
	log.Printf("rowAffected=%d, lastInsertId=%d \n", rowsAffected, lastInsertId)
}
